<template>
  <div class="checkout-container">
    <div class="header-nav">
      <el-button
        type="primary"
        icon="el-icon-back"
        @click="goBack"
        class="back-btn"
      >
        返回购物车
      </el-button>
    </div>
    <el-card class="checkout-card">
      <div class="order-summary">
        <h2>订单确认</h2>
        <el-table
          :data="cartItems"
          stripe
          style="width: 100%;"
        >
          <el-table-column prop="title" label="商品名称" width="300"></el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template slot-scope="scope">
              ¥ {{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
          <el-table-column label="小计" width="120">
            <template slot-scope="scope">
              ¥ {{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="payment-section">
        <h3>支付方式</h3>
        <el-radio-group v-model="paymentMethod">
          <el-radio label="alipay">支付宝</el-radio>
          <el-radio label="wechat">微信支付</el-radio>
          <el-radio label="card">银行卡</el-radio>
        </el-radio-group>
      </div>

      <div class="total-section">
        <div class="total-item">
          <span>商品总额：</span>
          <span>¥ {{ totalPrice.toFixed(2) }}</span>
        </div>
        <div class="total-item">
          <span>运费：</span>
          <span>¥ {{ shipping.toFixed(2) }}</span>
        </div>
        <div class="total-item grand-total">
          <span>应付总额：</span>
          <span class="price">¥ {{ finalTotal.toFixed(2) }}</span>
        </div>
      </div>

      <div class="submit-section">
        <el-button
          type="primary"
          size="large"
          @click="submitOrder"
          :loading="isSubmitting"
        >
          提交订单
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'CheckoutView',
  data() {
    return {
      paymentMethod: 'alipay',
      shipping: 10,
      isSubmitting: false
    };
  },
  computed: {
    cartItems() {
      return this.$store.state.cartItems;
    },
    totalPrice() {
      return this.$store.getters.cartTotal;
    },
    finalTotal() {
      return this.totalPrice + this.shipping;
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    async submitOrder() {
      if (this.isSubmitting) return;
      
      if (!this.$store.state.user) {
        this.$message.warning('请先登录');
        this.$router.push({
          path: '/login',
          query: { redirect: '/checkout' }
        });
        return;
      }

      if (this.cartItems.length === 0) {
        this.$message.warning('购物车为空');
        return;
      }

      this.isSubmitting = true;
      try {
        // 模拟订单提交
        await new Promise(resolve => setTimeout(resolve, 1500));
        
        // 创建订单，使用最新的总价
        const order = {
          id: Date.now(),
          items: [...this.cartItems],
          totalAmount: this.finalTotal,
          paymentMethod: this.paymentMethod,
          status: 'pending',
          createTime: new Date().toLocaleString()
        };

        // 保存订单
        this.$store.commit('addOrder', order);
        
        // 清空购物车
        this.$store.commit('clearCart');
        
        this.$message.success('订单提交成功！');
        this.$router.push('/orders');
      } catch (error) {
        this.$message.error('订单提交失败，请重试');
      } finally {
        this.isSubmitting = false;
      }
    }
  },
  created() {
    // 检查用户登录状态
    if (!this.$store.state.user) {
      this.$message.warning('请先登录');
      this.$router.push({
        path: '/login',
        query: { redirect: '/checkout' }
      });
      return;
    }

    // 检查购物车是否为空
    if (this.cartItems.length === 0) {
      this.$message.warning('购物车为空');
      this.$router.push('/cart');
      return;
    }

    // 确保获取最新的购物车数据
    this.$store.dispatch('syncCartData');
  },
  watch: {
    cartItems: {
      handler() {
        // 当购物车数据变化时，确保页面数据更新
        this.$forceUpdate();
      },
      deep: true
    }
  }
};
</script>

<style scoped>
.checkout-container {
  padding: 30px;
  background: #f5f7fa;
  min-height: 100vh;
}

.checkout-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.header-nav {
  margin-bottom: 20px;
}

.back-btn {
  padding: 12px 25px;
  border-radius: 8px;
  transition: all 0.3s;
}

.back-btn:hover {
  transform: translateX(-5px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.order-summary {
  margin-bottom: 30px;
}

.order-summary h2 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 1.5rem;
}

.payment-section {
  margin: 30px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.payment-section h3 {
  margin-bottom: 15px;
  color: #303133;
}

.total-section {
  margin: 30px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.total-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #606266;
}

.grand-total {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #dcdfe6;
  font-size: 1.2rem;
  font-weight: bold;
  color: #303133;
}

.price {
  color: #f56c6c;
}

.submit-section {
  text-align: center;
  margin-top: 30px;
}

.submit-section .el-button {
  padding: 15px 40px;
  font-size: 1.1rem;
  border-radius: 8px;
  transition: all 0.3s;
}

.submit-section .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.submit-section .el-button:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.1);
}
</style> 